﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BLL;
using PagedList;
using DLL;
using CommonHelpers;
using QuanLyBanLe.Depository;
using CheckComboBoxTest;

namespace QuanLyBanLe
{
    public partial class FormProductStatistics : Form
    {
        public List<pStatisticProduct_Result> ProductReport;
        private ProductService m_ProductService;
        private ProducerService m_ProducerService;
        private ProductTypeService m_ProductTypeService;
        private InProductService m_InOutProductService;
        private List<pStatisticProduct_Result> m_Products;
        private IList<Producer> m_Producers;
        private IList<ProductType> m_ProductTypes;
        private int m_PageNumber;
        private int m_PageSize;
        private int m_MaxPage;
        private bool m_EnabledEvent;
        private int m_TotalRecord;
        private bool m_IsFiltered;
        private SortOrder m_SortOrder;
        private string m_SortColumn;
        private CheckBox checkboxHeader;
        private bool isChecked;
        private bool editRow;

        public FormProductStatistics()
        {
            m_IsFiltered = false;
            m_ProducerService = new ProducerService();
            m_ProductTypeService = new ProductTypeService();
            m_ProductService = new ProductService();
            m_InOutProductService = new InProductService();
            m_PageNumber = 1;
            m_PageSize = 20;
            m_SortOrder = SortOrder.Ascending;
            m_EnabledEvent = false;
            InitializeComponent();
            dtgProductStatistic.AutoGenerateColumns = false;
            ProductReport = new List<pStatisticProduct_Result>();
        }

        private void btnFirst_Click(object sender, EventArgs e)
        {
            m_PageNumber = 1;
            ChangePageProductStatistic();
        }

        private void btnPrev_Click(object sender, EventArgs e)
        {
            m_PageNumber = m_PageNumber > 1 ? m_PageNumber - 1 : m_PageNumber;
            ChangePageProductStatistic();

        }

        private void mnrPageIndex_ValueChanged(object sender, EventArgs e)
        {
            if (m_EnabledEvent)
            {
                m_PageNumber = Convert.ToInt32(mnrPageIndex.Value);
                ChangePageProductStatistic();
            }
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            m_PageNumber = m_PageNumber < m_MaxPage ? m_PageNumber + 1 : m_PageNumber;
            ChangePageProductStatistic();
        }

        private void btnLast_Click(object sender, EventArgs e)
        {
            m_PageNumber = m_MaxPage;
            ChangePageProductStatistic();
        }


        private void SetEnabledForPagingNavigator()
        {
            if (m_PageNumber == m_MaxPage)
            {
                if (m_PageNumber == 1)
                {
                    btnFirst.Enabled = false;
                    btnPrev.Enabled = false;
                    btnLast.Enabled = false;
                    btnNext.Enabled = false;
                }
                else
                {
                    btnFirst.Enabled = true;
                    btnPrev.Enabled = true;
                    btnLast.Enabled = false;
                    btnNext.Enabled = false;
                }
            }
            else if (m_PageNumber == 1)
            {
                btnFirst.Enabled = false;
                btnPrev.Enabled = false;
                btnLast.Enabled = true;
                btnNext.Enabled = true;
            }
            else
            {
                btnFirst.Enabled = true;
                btnPrev.Enabled = true;
                btnLast.Enabled = true;
                btnNext.Enabled = true;
            }
        }


        private void FormProductStatistics_Load(object sender, EventArgs e)
        {
            int totalInputPrice = 0;
            m_Products = m_ProductService.StatisticsProduct(out totalInputPrice);
            BindProductInfoToGrid();
            lblTotalInputPrice.Text = totalInputPrice.ToMoney();
            BindProducer();
            BindProductType();
            Rectangle rect = dtgProductStatistic.GetCellDisplayRectangle(10, -1, true);
            rect.Y = 3;
            rect.X = rect.Location.X + (rect.Width / 8);
            checkboxHeader = new CheckBox();
            checkboxHeader.Name = "checkboxHeader";
            checkboxHeader.Size = new Size(18, 18);
            checkboxHeader.Location = rect.Location;
            checkboxHeader.CheckedChanged += new EventHandler(checkboxHeader_CheckedChanged);
            dtgProductStatistic.Controls.Add(checkboxHeader);
            dtgProductStatistic.Columns["colReport"].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            this.Text += FormMain.GetShopInfo();
        }

        void checkboxHeader_CheckedChanged(object sender, EventArgs e)
        {
            isChecked = false;
            if (editRow == false)
            {
                var checkbox = (CheckBox)sender;
                bool value = checkbox.Checked;
                for (int i = 0; i < dtgProductStatistic.Rows.Count; i++)
                {
                    dtgProductStatistic.Rows[i].Cells["colReport"].Value = value;
                }
            }
            isChecked = true;
        }

        public int FilterProduct()
        {
            int totalInputPrice = 0;
            string productTypeIds = null;
            int i = 0;
            foreach (CCBoxItem item in clbProductType.CheckedItems)
            {
                productTypeIds += item.Value.ToString();
                if (i < clbProductType.CheckedItems.Count - 1)
                {
                    productTypeIds += ",";
                }
                i++;
            }

            int? producerId = Convert.ToInt32(cboProducer.SelectedValue);
            if (producerId == 0)
            {
                producerId = null;
            }

            string productName = txtProduct.Text;
            if (string.IsNullOrWhiteSpace(productName))
            {
                productName = null;
            }

            bool checkWarningAmount = cbNoRemain.Checked;
            bool inputPriceChanged = cboInputPriceChange.Checked;

            m_Products = m_ProductService.StatisticsProduct(out totalInputPrice,
                productTypeIds, producerId, productName, checkWarningAmount, inputPriceChanged);
            return totalInputPrice;
        }

        private void ChangePageProductStatistic()
        {
            BindProductInfoToGrid();
            int numberRows = 0;
            if (isChecked)
            {
                editRow = true;
                foreach (DataGridViewRow row in dtgProductStatistic.Rows)
                {
                    if (Convert.ToBoolean(row.Cells["colReport"].Value) == false)
                    {
                        break;
                    }
                    numberRows++;
                }
                var checkbox = ((CheckBox)dtgProductStatistic.Controls.Find("checkboxHeader", true)[0]);
                if (numberRows == dtgProductStatistic.Rows.Count)
                {
                    checkbox.Checked = true;
                }
                else
                {
                    checkbox.Checked = false;
                }
                editRow = false;
            }
        }

        private void BindProductInfoToGrid()
        {
            int index = 1;
            dtgProductStatistic.Rows.Clear();
            IPagedList<pStatisticProduct_Result> products = null;
            if (m_SortOrder == SortOrder.Ascending)
            {
                if (m_SortColumn == "colAmount")
                {
                    products = m_Products.OrderBy(x => x.Amount).ToPagedList(m_PageNumber, m_PageSize);
                }
                else if (m_SortColumn == "colTotalInputPrice")
                {
                    products = m_Products.OrderBy(x => x.TotalInputPrice).ToPagedList(m_PageNumber, m_PageSize);
                }
                else if (m_SortColumn == "colSecondLatestInputPrice")
                {
                    products = m_Products.OrderBy(x => x.SecondLatestInputPrice).ToPagedList(m_PageNumber, m_PageSize);
                }
                else if (m_SortColumn == "colLatestInputPrice")
                {
                    products = m_Products.OrderBy(x => x.LatestInputPrice).ToPagedList(m_PageNumber, m_PageSize);
                }
                else if (m_SortColumn == "colProductType")
                {
                    products = m_Products.OrderBy(x => x.ProductTypeName).ToPagedList(m_PageNumber, m_PageSize);
                }
                else if (m_SortColumn == "colProducer")
                {
                    products = m_Products.OrderBy(x => x.ProducerName).ToPagedList(m_PageNumber, m_PageSize);
                }
                else if (m_SortColumn == "colProductName")
                {
                    products = m_Products.OrderBy(x => x.Name).ToPagedList(m_PageNumber, m_PageSize);
                }
                else
                {
                    products = m_Products.ToPagedList(m_PageNumber, m_PageSize);
                }
            }
            else
            {
                if (m_SortColumn == "colAmount")
                {
                    products = m_Products.OrderByDescending(x => x.Amount).ToPagedList(m_PageNumber, m_PageSize);
                }
                else if (m_SortColumn == "colTotalInputPrice")
                {
                    products = m_Products.OrderByDescending(x => x.TotalInputPrice).ToPagedList(m_PageNumber, m_PageSize);
                }
                else if (m_SortColumn == "colSecondLatestInputPrice")
                {
                    products = m_Products.OrderByDescending(x => x.SecondLatestInputPrice).ToPagedList(m_PageNumber, m_PageSize);
                }
                else if (m_SortColumn == "colLatestInputPrice")
                {
                    products = m_Products.OrderByDescending(x => x.LatestInputPrice).ToPagedList(m_PageNumber, m_PageSize);
                }
                else if (m_SortColumn == "colProductType")
                {
                    products = m_Products.OrderByDescending(x => x.ProductTypeName).ToPagedList(m_PageNumber, m_PageSize);
                }
                else if (m_SortColumn == "colProducer")
                {
                    products = m_Products.OrderByDescending(x => x.ProducerName).ToPagedList(m_PageNumber, m_PageSize);
                }
                else if (m_SortColumn == "colProductName")
                {
                    products = m_Products.OrderByDescending(x => x.Name).ToPagedList(m_PageNumber, m_PageSize);
                }
                else
                {
                    products = m_Products.ToPagedList(m_PageNumber, m_PageSize);
                }
            }

            foreach (var product in products.ToList())
            {
                var isReported = cbReport.Checked;
                if (!isReported)
                {
                    var productItem = ProductReport.Where(x => x.Id == product.Id).FirstOrDefault();
                    if (productItem != null)
                    {
                        isReported = true;
                    }
                    else
                    {
                        isReported = false;
                    }
                }
                dtgProductStatistic.Rows.Add((m_PageNumber - 1) * m_PageSize + index, product.Id,
                    product.ProductTypeName, product.ProducerName, product.Name, 
                    product.Amount, product.SecondLatestInputPrice, product.LatestInputPrice,
                    product.TotalInputPrice, product.SalePrice, isReported);
                index++;
            }
            m_TotalRecord = products.TotalItemCount;
            m_MaxPage = products.PageCount;
            if (m_TotalRecord > 0)
            {
                lblTotalPage.Text = "/" + m_MaxPage.ToString();
                mnrPageIndex.Minimum = 1;
                mnrPageIndex.Enabled = true;
                mnrPageIndex.Maximum = m_MaxPage;
                mnrPageIndex.Value = m_PageNumber;
                SetEnabledForPagingNavigator();
            }
            else
            {
                m_PageNumber = 0;
                mnrPageIndex.Minimum = 0;
                mnrPageIndex.Value = 0;
                mnrPageIndex.Enabled = false;
                btnFirst.Enabled = false;
                btnPrev.Enabled = false;
                btnLast.Enabled = false;
                btnNext.Enabled = false;
                lblTotalPage.Text = string.Empty;
            }
            m_EnabledEvent = true;
        }

        private void btnFilter_Click(object sender, EventArgs e)
        {
            m_EnabledEvent = false;

            m_PageNumber = 1;
            int totalInputPrice = FilterProduct();
            BindProductInfoToGrid();
            lblTotalInputPrice.Text = totalInputPrice.ToMoney();
            m_IsFiltered = true;
        }

        private void dtgProductStatistic_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == dtgProductStatistic.Columns["colInDetail"].Index)
            {
                int id = Convert.ToInt32(dtgProductStatistic["colId", e.RowIndex].Value.ToString());
                FormProductInDetailHistory form = new FormProductInDetailHistory(id);
                form.ShowDialog();
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }


        private void BindProductType()
        {
            m_ProductTypes = m_ProductTypeService.GetProductTypes();
            var productTypes = new List<ProductType>();
            productTypes.Add(new ProductType() { Id = 0, Name = "Tất cả" });
            productTypes.AddRange(m_ProductTypes);

            for (int i = 0; i < m_ProductTypes.Count; i++)
            {
                CCBoxItem item = new CCBoxItem(m_ProductTypes[i].Name, m_ProductTypes[i].Id);
                clbProductType.Items.Add(item);
            }
            clbProductType.MaxDropDownItems = 10;
            clbProductType.DisplayMember = "Name";
            clbProductType.ValueMember = "Id";
        }

        private void BindProducer()
        {
            m_Producers = m_ProducerService.GetProducers();
            var producers = new List<Producer>();
            producers.Add(new Producer() { Id = 0, Name = "Tất cả" });
            producers.AddRange(m_Producers);
            cboProducer.DataSource = producers;
            cboProducer.DropDownStyle = ComboBoxStyle.DropDown;
            cboProducer.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            cboProducer.AutoCompleteSource = AutoCompleteSource.ListItems;
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            if (m_IsFiltered)
            {
                for (int i = 0; i < clbProductType.Items.Count; i++)
                {
                    clbProductType.SetItemChecked(i, false);
                }
                cboProducer.SelectedValue = 0;
                txtProduct.Text = "";
                cbNoRemain.Checked = false;
                cboInputPriceChange.Checked = false;
                dtgProductStatistic.DataSource = null;
                dtgProductStatistic.Rows.Clear();
                m_IsFiltered = false;
            }
        }

        private void dtgProductStatistic_Sorted(object sender, EventArgs e)
        {
            var view = (DataGridView)sender;
            List<pStatisticProduct_Result> products = new List<pStatisticProduct_Result>();
            m_SortOrder = view.SortOrder;
            m_SortColumn = view.SortedColumn.Name;
            BindProductInfoToGrid();

        }

        private void cbReport_CheckedChanged(object sender, EventArgs e)
        {
            var rows = dtgProductStatistic.Rows;
            foreach (DataGridViewRow row in rows)
            {
                DataGridViewCheckBoxCell checkboxCell = (DataGridViewCheckBoxCell)row.Cells["colReport"];
                checkboxCell.Value = cbReport.Checked;
            }

        }

        private void btnPrintReport_Click(object sender, EventArgs e)
        {
            if (cbReport.Checked)
            {
                ProductReport = m_Products;
            }
            ProductReport = ProductReport.OrderBy(x => x.ProductTypeName)
                .ThenBy(x => x.ProducerName).ThenBy(x => x.Name).ToList();
            FormProductStatisticPrint form = new FormProductStatisticPrint(ProductReport);
            form.ShowDialog();
        }

        private void dtgProductStatistic_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex != -1 && e.ColumnIndex == dtgProductStatistic["colReport", e.RowIndex].ColumnIndex)
            {
                var report = Convert.ToBoolean(dtgProductStatistic["colReport", e.RowIndex].Value);
                var id = Convert.ToInt32(dtgProductStatistic["colId", e.RowIndex].Value);
                var product = m_Products.Where(x => x.Id == id).FirstOrDefault();

                if (report == true)
                {
                    ProductReport.Add(product);
                }
                else
                {
                    ProductReport.Remove(product);
                }
                int numberRows = 0;
                if (isChecked)
                {
                    editRow = true;
                    foreach (DataGridViewRow row in dtgProductStatistic.Rows)
                    {
                        if (Convert.ToBoolean(row.Cells["colReport"].Value) == false)
                        {
                            break;
                        }
                        numberRows++;
                    }
                    var checkbox = ((CheckBox)dtgProductStatistic.Controls.Find("checkboxHeader", true)[0]);
                    if (numberRows == dtgProductStatistic.Rows.Count)
                    {
                        checkbox.Checked = true;
                    }
                    else
                    {
                        checkbox.Checked = false;
                    }
                    editRow = false;
                }
            }
        }

        private void clbProductType_DropDownClosed(object sender, EventArgs e)
        {
            foreach (CCBoxItem item in clbProductType.CheckedItems)
            {
                int a = Convert.ToInt32(item.Value);
            }
        }

        private void cbo_KeyDown(object sender, KeyEventArgs e)
        {
            ComboBox cbo = sender as ComboBox;
            if (cbo.DroppedDown)
            {
                cbo.DroppedDown = false;
            }
        }
    }
}
